
from flask import Flask
from celery import Celery, Task
# from domain.ai_edit import tasks
# from tasks.task_signal_handler import *


def celery_init_app(flask_app: Flask = None):
    """Configure tasks.celery:

    * read configuration from app.config and update celery config
    * create a task context so tasks can access flask.current_app

    Doing so is recommended by flask documentation:
    https://flask.palletsprojects.com/en/2.3.x/patterns/celery/
    """
    # 这么做的目的应该主要是为了让celery的任务可以拿到flask app相关的上下文
    #   但为什么一定这么做更好暂时不确定
    # class FlaskTask(Task):
    #     def __call__(self, *args: object, **kwargs: object) -> object:
    #         with flask_app.app_context():
    #             return self.run(*args, **kwargs)

    celery_app = Celery(
        __name__,
        # include=["domain/ai_edit"], # 需要用include指定task文件所在的位置，否则无法找到task
        # task_cls=FlaskTask
    )
    init_config = flask_app.config['CELERY_CONFIG']
    print("init config: {}".format(init_config))
    celery_app.config_from_object(init_config)

    celery_app.set_default()
    if flask_app:
        flask_app.extensions["celery"] = celery_app
    return celery_app


# celery = celery_init_app()
